import os
import sys
import threading
import time
import tkinter as tk
from tkinter import Listbox, Scrollbar

import pyfiglet

##############################
# 获取当前文件的绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取 src 目录的父目录
parent_dir = os.path.dirname(current_dir)
# 将父目录添加到 sys.path
sys.path.append(parent_dir)
##############################
from src import upload, ascPro, download, cleaner
import basicConfig

##############################
# 上传文件夹目录
files_up_dir = basicConfig.ASC_FILE_DIR
# 临时文件夹
temp_files_dir = basicConfig.TEMP_FILE_DIR
# 全局配置参数
config = basicConfig.UI_CONFIG
# 全局变量
upload_listbox = None
temp_listbox = None
start_letter = "Transformer"
start_letter_font = "slant"
letter_color = "GREEN"


##############################
def print_hollow_letter():
    # 生成空心字母
    pyfiglet.print_figlet(start_letter, font=start_letter_font, colors=letter_color)


def update_file_list(listbox, directory):
    """
    更新指定 Listbox 中的文件列表

    :param listbox: 需要更新的 Listbox 控件
    :param directory: 需要列出文件的目录路径
    """
    listbox.delete(0, tk.END)
    files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
    for file in files:
        listbox.insert(tk.END, file)


# 标志位，用于控制线程是否应该停止
stop_event = threading.Event()


def update_file_listbox():
    while not stop_event.is_set():
        try:
            update_file_list(upload_listbox, files_up_dir)
            update_file_list(temp_listbox, temp_files_dir)
        except tk.TclError:
            # 如果发生 TclError，说明窗口已经关闭，停止线程
            stop_event.set()
            print(f'{tk.TclError}，主窗口已关闭，请及时关闭控制台...')
        time.sleep(1)  # 间隔 1 秒


def on_upload():
    try:
        uploader = upload.FileUploader()
        uploader.run()
    except Exception as e:
        ascPro.message_show("error", str(e))


def on_download():
    try:
        downloader = download.FileDownloader()
        downloader.run()
    except Exception as e:
        ascPro.message_show("error", str(e))


def on_convert():
    try:
        ascPro.transfer_files(files_up_dir, temp_files_dir)
    except Exception as e:
        ascPro.message_show("error", str(e))


def on_process():
    try:
        ascPro.process_files(temp_files_dir)
    except Exception as e:
        ascPro.message_show("error", str(e))


def on_clean():
    try:
        cleaner.clear_all()
    except Exception as e:
        ascPro.message_show("error", str(e))


def create_gui():
    global upload_listbox, temp_listbox
    root = tk.Tk()
    root.title("ASCII文件转换工具")
    # 获取屏幕的宽度和高度
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    # 计算窗口位置（x, y），使其位于屏幕中央
    x = (screen_width - config['root_width']) // 2
    y = (screen_height - config['root_height']) // 2
    root.geometry(f"{config['root_width']}x{config['root_height']}+{x}+{y}")  # 调整窗口大小和位置
    root.configure(bg=config["root_bg_color"])  # 设置根窗口背景色为灰色
    root.resizable(width=False, height=False)  # 禁止窗口被最大化.
    # 创建文件显示框容器
    file_frames_container = tk.Frame(root, bg=config["frame_bg_color"], bd=0, relief=tk.SUNKEN)
    file_frames_container.pack(pady=config["label_padding"], padx=config["label_padding"], side=tk.TOP,
                               anchor=tk.CENTER)
    # 创建上传文件显示框
    upload_frame = tk.Frame(file_frames_container, width=config["listbox_frame_width"],
                            height=config["listbox_frame_height"], bg=config["listbox_bg_color"])
    upload_frame.grid(row=0, column=0, padx=config["label_padding"], pady=config["label_padding"])
    upload_label = tk.Label(upload_frame, text="上传文件夹", bg=config["listbox_bg_color"])
    upload_label.pack(side=tk.TOP, pady=(0, config["label_padding"]))
    upload_listbox = Listbox(upload_frame, width=config["files_win_width"], height=config["files_win_height"],
                             bg=config["listbox_bg_color"])
    upload_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    upload_scrollbar = Scrollbar(upload_frame, command=upload_listbox.yview)
    upload_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    upload_listbox.config(yscrollcommand=upload_scrollbar.set)
    # 创建临时文件显示框
    temp_frame = tk.Frame(file_frames_container, width=config["listbox_frame_width"],
                          height=config["listbox_frame_height"], bg=config["listbox_bg_color"])
    temp_frame.grid(row=0, column=1, padx=config["label_padding"], pady=config["label_padding"])
    temp_label = tk.Label(temp_frame, text="临时文件夹", bg=config["listbox_bg_color"])
    temp_label.pack(side=tk.TOP, pady=(0, config["label_padding"]))
    temp_listbox = Listbox(temp_frame, width=config["files_win_width"], height=config["files_win_height"],
                           bg=config["listbox_bg_color"])
    temp_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    temp_scrollbar = Scrollbar(temp_frame, command=temp_listbox.yview)
    temp_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    temp_listbox.config(yscrollcommand=temp_scrollbar.set)
    # 创建按钮
    button_frame = tk.Frame(root, bg=config["frame_bg_color"], bd=0, relief=tk.SUNKEN)
    button_frame.pack(side=tk.BOTTOM, pady=config["label_padding"], padx=config["label_padding"])
    num_buttons = 4
    total_button_width = num_buttons * (config["button_width"] + config["button_padding"])  # 包括按钮之间的间距
    x_offset = (root.winfo_reqwidth() - total_button_width) // 2  # 居中对齐
    upload_button = tk.Button(button_frame, text="上传文件", command=on_upload, width=config["button_width"],
                              height=config["button_height"])
    upload_button.grid(row=0, column=0, padx=config["button_padding"])
    convert_button = tk.Button(button_frame, text="转换文件", command=on_convert, width=config["button_width"],
                               height=config["button_height"])
    convert_button.grid(row=0, column=1, padx=config["button_padding"])
    process_button = tk.Button(button_frame, text="处理文件", command=on_process, width=config["button_width"],
                               height=config["button_height"])
    process_button.grid(row=0, column=2, padx=config["button_padding"])
    download_button = tk.Button(button_frame, text="下载文件", command=on_download, width=config["button_width"],
                                height=config["button_height"])
    download_button.grid(row=0, column=3, padx=config["button_padding"])
    clean_button = tk.Button(button_frame, text="清理文件", command=on_clean, width=config["button_width"],
                             height=config["button_height"])
    clean_button.grid(row=0, column=4, padx=config["button_padding"])

    # 初始化文件列表
    file_update_thread = threading.Thread(target=update_file_listbox, daemon=True)
    file_update_thread.start()

    def on_closing():
        # 设置停止标志位，并等待线程停止
        stop_event.set()
        file_update_thread.join()
        root.destroy()

    root.protocol("WM_DELETE_WINDOW", on_closing)
    root.mainloop()


if __name__ == "__main__":
    print_hollow_letter()
    create_gui()
